package com.feng.job;

import com.feng.entity.Article;
import com.feng.service.ArticleService;
import com.feng.utils.Const;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class UpdateViewCountJob {

    final
    ArticleService articleService;

    final
    RedisTemplate redisTemplate;

    public UpdateViewCountJob(ArticleService articleService, RedisTemplate redisTemplate) {
        this.articleService = articleService;
        this.redisTemplate = redisTemplate;
    }

    @Scheduled(cron = "0 0/3 * * * ?")
    public void updateViewCount(){
        Map<String, Integer> cacheMap = redisTemplate.opsForHash().entries(Const.REDIS_VIEW_COUNT_KET);
        List<Article> articles = cacheMap.entrySet()
                .stream()
                .parallel()
                .map(entry -> {
                    Article article = new Article();
                    article.setId(entry.getKey());
                    article.setViewCount(entry.getValue().longValue());
                    return article;
                })
                .collect(Collectors.toList());
        articleService.updateBatchById(articles);
    }
}
